import { defineStore } from 'pinia'
import { useRoutesStore } from '@/store/modules/routes'
import { Router } from 'vue-router'

const useRoutersStore = useRoutesStore()
export const useRoutesTagStore = defineStore('RouteTag', {
  state: () => ({
    router: [
      {
        title: '首页',
        path: '/home',
        close: false,
      },
    ],
    activeTagPath: '',
  }),
  actions: {
    // 添加 tagRouter 路由标签
    pushRouter(index: string) {
      this.activeTagPath = index
      useRoutersStore.menuRoutes.forEach((val) => {
        if (
          index === val.path &&
          !this.router.some((item) => item.title === val.meta.title)
        ) {
          this.router.push({
            title: val.meta.title,
            path: val.path,
            close: true,
          })
        }
        if (val.children) {
          val.children.forEach((val1) => {
            if (
              index === val1.path &&
              !this.router.some((item) => item.title === val1.meta.title)
            ) {
              this.router.push({
                title: val1.meta.title,
                path: val1.path,
                close: true,
              })
            }
          })
        }
      })
    },
    // 移除 tagRouter 路由标签
    removeRouter(tag: any, router: Router) {
      this.router = this.router.filter((val) => val.path !== tag.path)
      this.activeTagPath = this.router[this.router.length - 1].path
      router.push(this.activeTagPath)
    },
    // 关闭当前
    closeCurrent(router: Router) {
      if (this.router.length > 1) {
        this.router = this.router.filter(
          (val) => val.path !== this.router[this.router.length - 1].path,
        )
      }
      this.activeTagPath = this.router[this.router.length - 1].path
      router.push(this.activeTagPath)
    },
    // 关闭其他
    closeOther(router: Router) {
      this.router = this.router.filter((val) => {
        if (this.router.indexOf(val) === 0) return true
        if (val.path === this.activeTagPath) return true
        return false
      })
      router.push(this.activeTagPath)
    },
    closeAll(router: Router) {
      if (this.router.length > 0) {
        this.router = [this.router[0]]
        this.activeTagPath = this.router[0].path
        router.push(this.router[0].path)
      }
    },
  },
  persist: true, //开启持久化存储的配置
})
